package whereRU.frontEnd;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import whereRU.frontEnd.R;
import database.MapDbAdapter;

import XMLread.Building;
import XMLread.ParseCSVbuilding;
import XMLread.ParseCSVspace;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

/**
 * Main activity.  This activity is shown when the application is first started
 */
public class WhereRUActivity extends Activity implements Runnable {
	ArrayList<Building> buildings;
	ProgressDialog dialog;
	MapDbAdapter mapDbAdapter;

	/** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.whereru);

		// check to see if the database already exists
		// if it doesn't then we need to load the map data into the database
		File database = getApplicationContext().getDatabasePath(MapDbAdapter.MAP_DATABASE_NAME);
		if (!database.exists()) {
			dialog = ProgressDialog.show(this, "Loading Map Data", 
					"Please Wait...", true);
			Thread thread = new Thread(this);
			thread.start();       
		}
	}

	/**
	 * Called when the thread is started.
	 * This method runs in the background as the loading dialog shows
	 */
	public void run() {
		try {
			// parse the map data into the database
			AssetManager assets = getResources().getAssets();
			mapDbAdapter = new MapDbAdapter(this);
			ParseCSVbuilding.parse(
					(InputStream) assets.open("buildings_latLong.csv"), mapDbAdapter);
			ParseCSVspace.parse( 
					(InputStream) assets.open("spaces.csv"), mapDbAdapter);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// send message to the handler stating we are done parsing
		handler.sendEmptyMessage(0);
	}

	/**
	 * Called when the user clicks the directions button
	 */
	public void getDirections(View view) {
		startActivity(new Intent(this, DirectionsActivity.class));   	
	}

	/**
	 * Called when the user clicks the schedule button
	 * @param view
	 */
	public void classSchedule(View view) {
		startActivity(new Intent(this, CourseScheduleActivity.class));   	
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			dialog.dismiss();
		}
	};

}